import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
import service from '../utils/service'

const Index = () => import('../views/index')
const Login = () => import('../views/login')
const Message = () => import('../views/message')
const GoodList = () => import('../views/goodList')
const Error = () => import('../views/404')

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'login',
      component: Login
    }, {
      path: '/login',
      name: 'loginSecond',
      component: Login
    },
    {
      path: '/index',
      name: 'index',
      meta: {
        requireAuth: true
      },
      component: Index,
      children: [
        {
          path: 'message',
          name: 'message',
          component: Message
        },
        {
          path: 'goodList',
          name: 'goodList',
          component: GoodList
        }
      ]
    },
    {
      path: '*',
      name: 'error',
      component: Error
    }
  ],
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return {x: 0, y: 0}
    }
  }
})

router.beforeEach(async (to, from, next) => {
  if (to.matched.some(record => record.meta.requireAuth)) { // 检查是否需要登录校验
    if (!store.getters.getAuth) { // 检查是否已登录
      if (store.getters.getToken) { // 未登录，但是有token，获取用户信息
        store.dispatch('setUserInfo', {userName: 'admin', userSign: '123456'})
        next()
      } else {
        service.showMessage('请登录')
        next({name: 'login'})
      }
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
